#include "basicwindows.h"

#include "CommonUtils.h"
#include "NotifyManager.h"

#include <QApplication>
#include <QDebug>
#include <QDesktopWidget>
#include <QFile>
#include <QGraphicsDropShadowEffect>
#include <QGuiApplication>
#include <QMouseEvent>
#include <QPainter>
#include <QScreen>
#include <QStyleOption>
#include <qmath.h>

BasicWindows::BasicWindows(QWidget* parent)
    : QDialog(parent) {
    if (!parent) {
        colorBackGround = CommonUtils::getDefaultSkinColor();
        setWindowFlags(Qt::FramelessWindowHint);
        setAttribute(Qt::WA_TranslucentBackground, true);
        setAttribute(Qt::WA_NoSystemBackground, false);

        connect(NotifyManager::getInstance(), SIGNAL(singnalSkinChanged(const QColor&)),
            this, SLOT(onSignalSkinChanged(const QColor&)));
    }
}

BasicWindows::~BasicWindows() {
}

// 皮肤改变
void BasicWindows::onSignalSkinChanged(const QColor& color) {
    colorBackGround = color;
    loadStyleSheet(styleName);
}

void BasicWindows::setTitleBarTitle(const QString& title, const QString& icon) {
    titleBar->setTitleIcon(icon);
    titleBar->setTitleContent(title);
}

void BasicWindows::saveRestoreInfo(const QRect& rect) {
    restoreRect = rect;
}

QRect BasicWindows::getRestoreInfo() {
    return restoreRect;
}

void BasicWindows::moveMouseToPosition(const QPoint& position) {
    QCursor cursor;
    auto    p = (position);
    cursor.setPos(p);
}
void BasicWindows::initTitleBar(ButtonType buttonType) {
    titleBar = new TitleBar(this);
    titleBar->setButtonType(buttonType);

    titleBar->setTitleWidth(width() - 20);
    titleBar->move(10, 10);
    titleBar->enableMove(true);

    connect(titleBar, SIGNAL(signalButtonMinClicked()), this, SLOT(onButtonMinClicked()));
    connect(titleBar, SIGNAL(signalButtonMaxClicked()), this, SLOT(onButtonMaxClicked()));
    connect(titleBar, SIGNAL(signalButtonRestoreClicked()), this, SLOT(onButtonRestoreClicked()));
    connect(titleBar, SIGNAL(signalButtonCloseClicked()), this, SLOT(onButtonCloseClicked()));
}

void BasicWindows::initTitleBar(TitleBar* titlebar) {
    connect(titleBar, SIGNAL(signalButtonMinClicked()), this, SLOT(onButtonMinClicked()));
    // connect(titleBar, &TitleBar::signalButtonMinClicked, this, &BasicWindows::onButtonMinClicked);
    connect(titleBar, SIGNAL(signalButtonMaxClicked()), this, SLOT(onButtonMaxClicked()));
    connect(titleBar, SIGNAL(signalButtonRestoreClicked()), this, SLOT(onButtonRestoreClicked()));
    connect(titleBar, SIGNAL(signalButtonCloseClicked()), this, SLOT(onButtonCloseClicked()));
}

void BasicWindows::loadStyleSheet(const QString& sheetName) {
    this->styleName = sheetName;
    QFile file(":/css/" + sheetName + ".css");
    file.open(QFile::ReadOnly);

    if (file.isOpen()) {
        setStyleSheet("");
        QString qsstyleSheet;
        qsstyleSheet = QLatin1String(file.readAll());

        QString r = QString::number(colorBackGround.red());
        QString g = QString::number(colorBackGround.green());
        QString b = QString::number(colorBackGround.blue());

        qsstyleSheet += QString("\
			QWidget[titleskin=true]\
			{background-color:rgb(%1,%2,%3);\
			border-top-right-radius:4px;\
			border-top-left-radius:4px;}\
			QWidget[bottomskin=true]\
			{border-top:1px solid rgba(%1,%2,%3,100);\
			background-color:rgba(%1,%2,%3,50);\
			border-bottom-left-radius:4px;\
			border-bottom-right-radius:4px;}")
                            .arg(r)
                            .arg(g)
                            .arg(b);

        setStyleSheet(qsstyleSheet);
        file.close();
    }
}

/// <summary>
/// 初始化背景颜色
/// </summary>
void BasicWindows::initBackGroundColor() {
    QStyleOption opt;
    opt.init(this);

    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

/// <summary>
///
/// </summary>
/// <param name="event"></param>
void BasicWindows::paintEvent(QPaintEvent* event) {
    // initBackGroundColor();
    drawShadow();
    QDialog::paintEvent(event);
}

/// <summary>
/// 头像转换为圆头像
/// </summary>
/// <param name="src"></param>
/// <param name="mask"></param>
/// <param name="masksize"></param>
/// <returns></returns>
QPixmap BasicWindows::getRoundImage(const QPixmap& src, QPixmap& mask, QSize masksize) {
    if (masksize == QSize(0, 0)) {
        masksize = mask.size();
    }
    else {
        mask = mask.scaled(masksize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    }

    // 保存转换后的头像
    QImage   resultImage(masksize, QImage::Format_ARGB32_Premultiplied);
    QPainter painter(&resultImage);
    painter.setCompositionMode(QPainter::CompositionMode_Source);
    painter.fillRect(resultImage.rect(), Qt::transparent);
    painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
    painter.drawPixmap(0, 0, mask);
    painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
    painter.drawPixmap(0, 0, src.scaled(masksize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    painter.end();

    return QPixmap::fromImage(resultImage);
}

void BasicWindows::mouseMoveEvent(QMouseEvent* event) {
    if (mousePressed && (event->buttons() & Qt::LeftButton)) {
        if (isMax) {
            auto info = getRestoreInfo();

            auto px = (float)event->globalPos().x() / rect().width();
            auto py = (float)event->globalPos().y() / rect().height();
            auto x  = px * info.width();
            auto y  = py * info.height();

            qDebug() << QString("info [%1, %2] [%3, %4] [%5, %6]")
                            .arg(info.x())
                            .arg(info.y())
                            .arg(x)
                            .arg(y)
                            .arg(px)
                            .arg(py);
            onShowRestore(info);

            // 将鼠标移动到指定坐标
            moveMouseToPosition(QPoint(x + info.x(), y + info.y()));
            mousePoint = QPoint(x, y);

            // info.setX(x);
            // info.setY(y);

            emit signalWindowRestore();
        }
        else
            move(event->globalPos() - mousePoint);
        event->accept();
    }
}
void BasicWindows::mousePressEvent(QMouseEvent* event) {
    if (event->button() == Qt::LeftButton) {
        mousePressed = true;
        mousePoint   = event->globalPos() - pos();
        event->accept();
    }
}
void BasicWindows::mouseReleaseEvent(QMouseEvent* event) {
    mousePressed = false;
}

void BasicWindows::onShowClose(bool) {
    close();
}
void BasicWindows::onShowMin(bool) {
    showMinimized();
}
void BasicWindows::onShowHide(bool) {
    hide();
}
void BasicWindows::onShowNormal(bool) {
    show();
    activateWindow();
}
void BasicWindows::onShowQuit(bool) {
    QApplication::quit();
}

void BasicWindows::onShowMax() {
    saveRestoreInfo(QRect(pos(), QSize(width(), height())));
    // QRect desktopRect = QApplication::desktop()->availableGeometry();

    // 返回一个 QRect 对象，表示主屏幕的可用几何形状。这个几何形状不包括系统任务栏和其他桌面装饰。
    QRect desktopRect = QGuiApplication::primaryScreen()->availableGeometry();

    QRect factRect = QRect(desktopRect.x() - 3, desktopRect.y() - 6,
        desktopRect.width() + 6, desktopRect.height() + 6);
    // setGeometry(factRect);
    setGeometry(desktopRect);
    isMax = true;

    setContentMargin(0);
    // showMaximized();
}

void BasicWindows::onShowRestore() {
    QRect rect = getRestoreInfo();
    onShowRestore(rect);
}

void BasicWindows::onShowRestore(const QRect& rect) {
    setGeometry(rect);

    isMax = false;

    setContentMargin(10);
}
void BasicWindows::onButtonMinClicked() {
    if (Qt::Tool == (windowFlags() & Qt::Tool)) {
        hide();
    }
    else {
        showMinimized();
    }
}

void BasicWindows::onButtonMaxClicked() {
    onShowMax();
}

void BasicWindows::onButtonRestoreClicked() {
    onShowRestore();
}

void BasicWindows::onButtonCloseClicked() {
    close();
}

void BasicWindows::drawShadow() {
    // QPainter painter(this);
    // painter.setRenderHint(QPainter::Antialiasing, true);

    // // 绘制阴影
    // QColor shadowColor(0, 0, 0, 100);
    // painter.setPen(Qt::NoPen);
    // painter.setBrush(shadowColor);

    // int shadowSize = 10;
    // QRect shadowRect = rect().adjusted(shadowSize, shadowSize, -shadowSize, -shadowSize);
    // QPainterPath shadowPath;
    // shadowPath.setFillRule(Qt::WindingFill);
    // shadowPath.addRoundedRect(shadowRect, 10, 10);
    // shadowPath.addRect(rect());

    // painter.drawPath(shadowPath);
    if (isMax) {
        return;
    };

    const auto SHADOW_WIDTH = 10;
    QPainter   painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);
    // painter.fillRect(QRect(SHADOW_WIDTH, SHADOW_WIDTH, this->width() - 2 * SHADOW_WIDTH, this->height() - 2 * SHADOW_WIDTH), QBrush(Qt::white));

    QColor color(50, 50, 50, 30);
    for (int i = 0; i < SHADOW_WIDTH; i++) {
        color.setAlpha(120 - qSqrt(i) * 40);
        painter.setPen(color);
        // 方角阴影边框;
        //   painter.drawRect(SHADOW_WIDTH - i, SHADOW_WIDTH - i, this->width() - (SHADOW_WIDTH - i) * 2, this->height() - (SHADOW_WIDTH - i) * 2);
        // 圆角阴影边框;
        painter.drawRoundedRect(SHADOW_WIDTH - i, SHADOW_WIDTH - i, this->width() - (SHADOW_WIDTH - i) * 2, this->height() - (SHADOW_WIDTH - i) * 2, 4, 4);
    }
}

void BasicWindows::setContentMargin(int margin) {
}

void BasicWindows::showTipText(QString text, QPoint point, int time) {
    QToolTip::showText(
        point,
        text,
        this,
        QRect(0, 0, 120, 100), time);
}

void BasicWindows::showTipText(QString text, int time) {
    auto p = cursor().pos();
    QToolTip::showText(
        QPoint(p.x() - 90, p.y() - 50),
        text,
        this,
        QRect(0, 0, 120, 100), time);
}
